package com.kaifamiao.jsp.servlet;

import com.kaifamiao.jsp.entity.Customer;
import com.kaifamiao.utils.JdbcHelper;
import com.kaifamiao.utils.RowHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@WebServlet( "/customer/edit" )
public class CustomerEditServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doGet(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        String idString = request.getParameter( "id" );
        logger.info( "准备修改[" + idString + "]对应的客户信息" );

        Integer id = Integer.valueOf( idString );

        JdbcHelper helper = JdbcHelper.getInstance();

        String sql = "SELECT id , username , password , nickname , name , gender , birthdate " +
                "FROM t_customers " +
                "WHERE id = ? " ;

        RowHandler<Customer> handler = new RowHandler<Customer>() {
            @Override
            public Customer handle(ResultSet rs) throws SQLException {
                Customer c = new Customer();
                c.setId( rs.getInt( "id" ) );
                c.setUsername( rs.getString( "username" ) );
                c.setPassword( rs.getString( "password" ) );
                c.setNickname( rs.getString( "nickname" ) );
                c.setName( rs.getString( "name" ) );
                c.setGender( rs.getString( "gender" ) );
                java.sql.Date date = rs.getDate( "birthdate" );
                LocalDate birthdate = date.toLocalDate();
                c.setBirthdate( birthdate );
                return c;
            }
        };

        Customer c = helper.single( sql , handler , id );

        helper.release();

        request.setAttribute( "customer" , c );

        request.getRequestDispatcher( "/WEB-INF/edit.jsp" ).forward( request , response );

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idString = request.getParameter( "id" );
        logger.info( "正在修改["+idString+"]对应的客户信息" );
        final String editURL = request.getContextPath() + "/customer/edit?id="+ idString ;
        // 如果校验失败
        if( !this.validate(request) ){
            response.sendRedirect( editURL );
            return ;
        }

        List<Object> list = new ArrayList<>();
        list.add( request.getParameter( "username" ) );
        list.add( request.getParameter( "password" ) );
        list.add( request.getParameter( "nickname" ) );
        list.add( request.getParameter( "name" ) );
        list.add( request.getParameter( "gender" ) );

        java.sql.Date birthdate = null ;
        String dateString = request.getParameter( "birthdate" );
        DateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
        try {
            java.util.Date utilDate = df.parse( dateString );
            birthdate = new java.sql.Date( utilDate.getTime() );
        } catch (ParseException e) {
            e.printStackTrace();
        }
        list.add( birthdate );

        Integer id = Integer.valueOf( idString );
        list.add( id );

        JdbcHelper helper = JdbcHelper.getInstance();
        String sql = "UPDATE t_customers " +
                     "SET username = ? , password = ? , nickname = ? , name = ? , gender = ? , birthdate = ? " +
                     "WHERE id = ? ";
        Object[] params = list.toArray() ;
        int count = helper.execute( sql , params );

        HttpSession session = request.getSession();
        if( count != 1 ) {
            session.setAttribute( "message" , "修改失败" );
            response.sendRedirect( editURL );
            return ;
        }

        session.setAttribute( "message" , "修改失败" );
        response.sendRedirect( request.getContextPath() + "/customer/list" );

    }

    /**
     * 对请求参数进行数据校验，以确保数据有效
     * @param request 表示请求对象
     * @return 当所有请求参数都通过检验时返回 true
     */
    private boolean validate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = request.getParameter( "username" );
        if( username == null || username.trim().isEmpty() ) {
            session.setAttribute( "message" , "用户名不能为空" );
            return false ;
        }
        String password = request.getParameter( "password" );
        if( password == null || password.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "密码不能为空" );
            return false ;
        }
        String confirm = request.getParameter( "confirm" );
        if( !password.equals( confirm )){
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "两次密码不一致" );
            return false ;
        }
        String nickname = request.getParameter( "nickname" );
        if( nickname == null || nickname.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "昵称不能为空" );
            return false ;
        }
        String name = request.getParameter( "name" );
        if( name == null || name.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "message" , "真实姓名不能为空" );
            return false;
        }
        String gender = request.getParameter( "gender" );
        if( gender == null || gender.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "name" , name );
            session.setAttribute( "message" , "请选择性别" );
            return false;
        }
        String birthdate = request.getParameter( "birthdate" );
        if( birthdate == null || birthdate.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "name" , name );
            session.setAttribute( "gender" , gender );
            session.setAttribute( "message" , "请选择出生日期" );
            return false ;
        }

        return true ;
    }
}
